package com.mccree.cloud.utils;

import cn.hutool.json.JSONUtil;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.bssopenapi.model.v20171214.QueryAccountBalanceRequest;
import com.aliyuncs.bssopenapi.model.v20171214.QueryAccountBalanceResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.mccree.cloud.common.AliQueryResp;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author: MccRee
 * @Date: 2022/6/20 10:09
 */
@Slf4j
public class AliyunUtil {
    private static IAcsClient client = null;

    private AliyunUtil(){}

    public static void main(String[] args) {
        String endPoint = "http://oss-cn-shenzhen.aliyuncs.com";
        String regionId = endPoint.substring(endPoint.indexOf("-") + 1, endPoint.indexOf("."));
        IAcsClient client = getClient("LTAI5tPJcNygr4g1JSC4dy5k", "W5dX9H6XUl1SiQt4956eUbVW6Yhpqf",regionId);
        AliQueryResp aliQueryResp = queryAccount(client);
        System.out.println(aliQueryResp);
    }

    /**
     * 初始化客户端对象
     * @param accessKeyId
     * @param accessKeySecret
     * @param regionId
     * @return
     */
    public static IAcsClient getClient(String accessKeyId, String accessKeySecret, String regionId){
        if (client == null){
            DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
            client = new DefaultAcsClient(profile);
        }
        return client;
    }

    /**
     * 查询阿里云用户余额
     * @param client
     * @throws Exception
     */
    public static AliQueryResp queryAccount(IAcsClient client) {
        QueryAccountBalanceRequest request = new QueryAccountBalanceRequest();
        QueryAccountBalanceResponse acsResponse = null;
        try {
            acsResponse = client.getAcsResponse(request);
        } catch (ServerException e) {
            log.error("QUERY_ACCOUNT_SERVER_ERR:",e);
        } catch (ClientException e){
            log.error("ErrCode:{}",e.getMessage());
            log.error("ErrMsg:{}",e.getErrMsg());
            log.error("RequestId:{}",e.getRequestId());
            log.error("QUERY_ACCOUNT_CLIENT_ERR:",e);
        }
        String msg = new Gson().toJson(acsResponse);
        return JSONUtil.toBean(msg,AliQueryResp.class);
    }

}
